package com.mjsoftking.paletteapp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.mjsoftking.palettelib.BasePalette;
import com.mjsoftking.palettelib.bean.PaletteDrawConfig;

import java.util.List;

/**
 * 用途：
 * <p>
 * 作者：MJSoftKing
 */
public class TestView extends androidx.appcompat.widget.AppCompatImageView implements BasePalette.IDraw {

    public BasePalette palette;

    public TestView(@NonNull Context context) {
        super(context);
        init();
    }

    public TestView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TestView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        palette = BasePalette.create(this);
//        palette.setEnableEndToEnd(true);
//        palette.setEnableOnce(true);

//        //重写为画多边形，此时绘制方法完全由此方法实现 todo 方法二
//        palette.setDraw((canvas, lines) -> {
//            for (PaletteDrawConfig config : lines) {
//                if(config.points.size() <= 1) continue;
//
//                Path path1 = new Path();
//                path1.moveTo(config.points.get(0).x, config.points.get(0).y);
//                for (int i = 1; i < config.points.size(); ++i) {
//                    path1.lineTo(config.points.get(i).x, config.points.get(i).y);
//                }
//                path1.close();//封闭
//                config.paint.setStyle(Paint.Style.STROKE);
//                canvas.drawPath(path1, config.paint);
//            }
//        });
    }

    /**
     * todo 方法一 实现{@link BasePalette.IDraw}接口，则无需手动设置绘制方法，默认进行了重绘
     * <p>
     * 重写为画多边形，此时绘制方法完全由此方法实现
     */
    public void onDraw(Canvas canvas, List<PaletteDrawConfig> lines) {
        for (PaletteDrawConfig config : lines) {
            if (config.points.size() <= 1) continue;

            Path path1 = new Path();
            path1.moveTo(config.points.get(0).x, config.points.get(0).y);
            for (int i = 1; i < config.points.size(); ++i) {
                path1.lineTo(config.points.get(i).x, config.points.get(i).y);
            }
            path1.close();//封闭
            config.paint.setStyle(Paint.Style.STROKE);
            canvas.drawPath(path1, config.paint);
        }
    }

    @Override
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouchEvent(MotionEvent event) {
        return palette.onTouchEvent(event) || super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        palette.onDraw(canvas);
    }
}
